package com.nasa.sentinel.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.company.nuwa.common.enumration.GlobalBizCode;
import com.company.nuwa.common.exception.BizException;
import com.nasa.sentinel.nacos.SentinelNacosConfigProperties;
import lombok.extern.slf4j.Slf4j;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * <p>block exception handler</p >
 *
 * @author youyoukele
 * @version 1.0
 * @date 2022/3/8
 */
@Slf4j
public class GlobalBlockExceptionHandler implements BlockExceptionHandler {

    private final SentinelNacosConfigProperties properties = SpringUtil.getApplicationContext().getBean(SentinelNacosConfigProperties.class);

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        log.error("block exception", e);
        throw new BizException(GlobalBizCode.FLOW_LIMITING.getCode(), ObjectUtil.defaultIfBlank(properties.getBlockTips(), GlobalBizCode.FLOW_LIMITING.getMessage()));
    }
}
